"""Build script."""

from setuptools import Extension, find_packages
from setuptools.command.build_ext import build_ext
from setuptools.errors import CCompilerError, ExecError, PlatformError

from Cython.Build import cythonize

example_modules = [
    # c函数pyx封装
    Extension(
        # 拓展模块全名, 与导入路径相关
        # 此外, 该名字带有校验__pyx_t_24example_cython_extension_8includes_18example_month_hall
        "example_cython_extension.includes.example_month_hall",
        sources=[
            "example_cython_extension/includes/example_month_hall.pyx",
            "src/libc/example_month_hall.c",
        ],
        include_dirs=["example_cython_extension/includes/internal"],
    ),
    # TODO: point1
    # ！！！不建议！！！
    # 此时模块名为includes.example_month_hall
    # 这是非常反人类的行为, 因为它处于example_cython_extension模块下, 按逻辑应该是example_cython_extension.includes.xxx
    # 实际上应该是includes.xxx, 同时需要手动修改sys.path以便匹配
    # Extension(
    #     "includes.example_month_hall",
    #     sources=[
    #         "example_cython_extension/includes/example_month_hall.pyx",
    #         "src/libc/example_month_hall.c",
    #     ],
    #     include_dirs=["example_cython_extension/includes/internal"],
    # ),
    Extension(
        "example_cython_extension.month_hall",
        sources=[
            "src/cython/example_month_hall.pyx",
        ],
    ),
]


class ExtBuilder(build_ext):
    def run(self):
        try:
            build_ext.run(self)
        except (PlatformError, FileNotFoundError):
            pass

    def build_extension(self, ext):
        try:
            build_ext.build_extension(self, ext)
        except (CCompilerError, ExecError, PlatformError, ValueError):
            pass


def build(setup_kwargs: dict):
    setup_kwargs.update({
        # 自动识别__init__.py文件并添加
        "packages": find_packages(),
        "package_dir": {
            # py模块名称, 实际文件路径
            "example_cython_extension": "example_cython_extension",
            # "includes": "example_cython_extension/includes",  # TODO: point1
        },
        "ext_modules": cythonize(
            example_modules,
            language_level="3",
            # cython链接路径，默认是"."
            # 这里不是头文件的路径, 而是pxd文件，当然实际运行依然是查找pyd
            # include_path=["example_cython_extension"],  # TODO: point1
        ),
        # 将编译结果复制回本模块，方便测试
        "script_args": ["build_ext", "--inplace"],
    })
